package com.kamfu.introduction;

import com.kamfu.function.common.List;

/**
 * 支付记录
 */
public class Payment03 {

    public final CreditCard creditCard;
    public final int amount;

    public Payment03(CreditCard creditCard, int amount) {
        this.creditCard = creditCard;
        this.amount = amount;
    }

    /**
     * 可以将多个支付记录合并
     * @param payment
     * @return
     */
    public Payment03 combine(Payment03 payment) {
        if (creditCard.equals(payment.creditCard)) {
            return new Payment03(creditCard, amount + payment.amount);
        } else {
            throw new IllegalStateException("Cards don't match.");
        }
    }

    /**
     * 按信用卡分组合并支付记录
     */
    public static List<Payment03> groupByCard(List<Payment03> payments) {
        return payments
                .groupBy(x -> x.creditCard)
                .values()
                .map(list -> list.reduce(c1 -> c1::combine));
    }
}
